package com.nf.xiaomi.dao.impl;

import com.nf.dbutils.SqlExecutor;
import com.nf.dbutils.handlers.BeanHandler;
import com.nf.dbutils.handlers.BeanListHandler;
import com.nf.dbutils.handlers.ScalarHandler;
import com.nf.xiaomi.dao.ShoppingCartDao;
import com.nf.xiaomi.entity.CartItemEntity;
import com.nf.xiaomi.util.SqlExecutorUtils;

import java.util.List;

public class ShoppingCartDaoImpl implements ShoppingCartDao {
    SqlExecutor executor= SqlExecutorUtils.getExecutor();
    @Override
    public int addItem(Integer userID, int detailID, Integer amount, String proName) {
        String sql="insert into cart(user_id,product_detail_id,amount,product_name)" +
                " values(?,?,?,?)";
        return executor.update(sql, userID, detailID, amount,proName);
    }

    @Override
    public int delItem(int itemID) {
        String sql="DELETE FROM cart WHERE cart_id=?";
        return executor.update(sql,itemID);
    }

    @Override
    public int setAmount(int cartID, Integer amount) {
        String sql="UPDATE cart SET amount=?" +
                " where cart_id=? ";
        return executor.update(sql,amount,cartID);
    }

    @Override
    public Integer getAmount(Integer cartID) {
        String sql="SELECT amount FROM cart WHERE cart_id=?";
        return executor.query(sql, new ScalarHandler<Integer>(), cartID);
    }

    @Override
    public Integer getCartID(Integer userID, int detailID){
        String sql="SELECT cart_id FROM cart where user_id=? and product_detail_id=?";
        return executor.query(sql, new ScalarHandler<Integer>(), userID, detailID);
    }

    @Override
    public List<CartItemEntity> getUserCartItemList(Integer userID) {
        String sql="SELECT c.cart_id,c.product_detail_id,pd.product_picture_list,c.amount,c.user_id,c.product_name FROM cart c\n" +
                "inner join product_detail pd on c.product_detail_id = pd.product_detail_id \n" +
                "WHERE c.user_id = ?";
        return executor.query(sql,new BeanListHandler<>(CartItemEntity.class),userID);
    }

    @Override
    public List<CartItemEntity> getCountAndSubtotal(Integer userID) {
        String sql="SELECT sum(c.amount) countAll,sum(pd.product_detail_price) subtotalAll FROM cart c\n" +
                "inner join product_detail pd on c.product_detail_id = pd.product_detail_id \n" +
                "WHERE c.user_id = ?";
        return executor.query(sql,new BeanListHandler<>(CartItemEntity.class),userID);
    }

    @Override
    public CartItemEntity getCartItem(int cartID) {
        String sql="SELECT c.cart_id,c.product_detail_id,pd.product_picture_list,c.amount,c.user_id,c.product_name FROM cart c\n" +
                "inner join product_detail pd on c.product_detail_id = pd.product_detail_id WHERE c.cart_id =?";
        return executor.query(sql,new BeanHandler<>(CartItemEntity.class),cartID);
    }


}
